package java8.collector.demo01;

import java8.lambda.demo01.Apple;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ChangLiang
 * @date 2020/4/23
 */
public class AppleCollector {

    public static Map<String, List<Apple>> groupAppleByColorPreviously(List<Apple> apples) {
        Map<String, List<Apple>> map = new HashMap<>(5);
        for (Apple a : apples) {
            List<Apple> list = map.get(a.getColor());
            if (null == list) {
                list = new ArrayList<>();
                map.put(a.getColor(), list);
            }
            list.add(a);
        }
        return map;
    }

    /**
     * 以函数式编程的方式 执行group
     * @param apples
     * @return
     */
    public static Map<String, List<Apple>> groupAppleByFunction(List<Apple> apples) {
        Map<String, List<Apple>> map = new HashMap<>(5);
        apples.stream().forEach(a->{
            List<Apple> colorList = Optional.ofNullable(map.get(a.getColor())).orElseGet(() -> {
                List<Apple> list = new ArrayList<>();
                map.put(a.getColor(), list);
                return list;
            });
            colorList.add(a);
        });
        return map;
    }

    /**
     * 以collector方式 执行group
     * @param apples
     * @return
     */
    public static Map<String, List<Apple>> groupAppleByCollector(List<Apple> apples) {
        Map<String, List<Apple>> collect = apples.stream().collect(Collectors.groupingBy(Apple::getColor));
        return collect;
    }
}
